package chapter1.zyq1_str_obj;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 第三版： 服务端可以让多个客户端链接。 同时一次可以和多个客户端通信(线程池实现)(发送文件)*/
public class Server4 {
    public static void main(String[] args) {
        Server4 server = new Server4();
        server.start();
    }

    //线程池，每个会话由一个线程处理
    private ExecutorService fixPool = Executors.newCachedThreadPool();
    public void start(){
        try {
            ServerSocket serverSocket = new ServerSocket(8001);
            System.out.println("服务器开启服务端口" + 8001 + ",等待连接请求...");
            while(true) {
                Socket socket = serverSocket.accept();
                System.out.println("接受客户端的连接，开始会话...");
                //设置服务端socket读超时为20000毫秒
                socket.setSoTimeout(1000);
                //把会话操作提交给线程池，由另外的线程单独处理会话。
                Thread t1=new Thread(){
                    public void run(){
                        try {
                            session(socket);
                            socket.close();
                            System.out.println("会话结束，服务端关闭连接。");
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                };
                fixPool.execute(t1);
                /*fixPool.execute(
                        ()->{
                            try {
                                session(socket);
                                socket.close();
                                System.out.println("会话结束，服务端关闭连接。");
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                );*/
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    protected void session(Socket socket) throws Exception {
        Student4 stu = Student4List.getStudent();
        sendReceiveUtil_Obj4.sendObject(socket, stu);
        System.out.println("发送对象: " + stu);
        stu = (Student4)sendReceiveUtil_Obj4.recvObject(socket);
        System.out.println("接收对象: " + stu);
        stu = (Student4)sendReceiveUtil_Obj4.recvObject(socket);
        System.out.println("接收对象: " + stu);
        List<Student4> stuList = Student4List.getStudents();
        sendReceiveUtil_Obj4.sendObject(socket, stuList);
        System.out.println("发送列表: " + stuList);
    }

}
